<?php

namespace app\data\controller\api\auth;

use app\data\controller\api\Auth;
use app\data\service\NewsService;
use think\Db;

/**
 * 文章评论内容
 * Class News
 * @package app\data\controller\api\auth
 */
class News extends Auth
{

    /**
     * 文章详情
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function details(){
        /*$data = $this->_vali([
            'c_id.require'      => '未找到该文章信息'
        ]);*/
        $data = input('post.');
        $map = [
            'id'            => $data['c_id'],
            'status'        => 1,
            'deleted'       => 0
        ];
        //存储用户阅读记录
        $history = [
            'cid'       => $data['c_id'],
            'mid'       => $this->mid
        ];

        $article = $this->app->db->name('data_news_item')
            ->where($map)
            ->find();
        if (empty($article)){
            $this->error('文章不存在');
        }else{
            if (!empty($article['publisher'])){
                $article += $this->app->db->name('data_member')->where('id='.$article['publisher'])->field('username,headimg')->find();
            }else{
                $article['username'] = "匿名用户";
                $article['headimg'] = 'https://api.hnsyc.com/safefile/后台管理员.jpg';
            }

            //判断是否访问过
            $is_visit = $this->app->db->name('data_news_x_history')->where(['cid'=>$data['c_id'],'mid'=>$this->mid])->find();
            if (empty($is_visit)){
                //第一次访问
                $this->app->db->startTrans();
                $res = $this->app->db->name('data_news_x_history')->insert($history);
                $res1 = $this->app->db->name('data_news_item')->where($map)->update(['num_read' => ($article['num_read'] + 1)]);
                if ($res && $res1){
                    $this->app->db->commit();
                    $this->success('获取成功',$article);
                }else{
                    $this->error('访问失败');
                    $this->app->db->rollback();
                }
            }else{
                //已经访问过
                $re_visit = $this->app->db->name('data_news_x_history')->where($history)->update(['create_at' => date('Y-m-d H:i:s',time())]);
                if ($re_visit){
                    $this->success('获取成功',$article);
                }else{
                    $this->error('获取失败');
                }
            }
        }
    }

    /**
     * 会员评论内容
     * @throws \think\db\exception\DbException
     */
    public function addComment()
    {
        /*$data = $this->_vali([
            'mid.value'       => $this->mid,
            'cid.require'     => '文章不能为空！',
            'content.require' => '内容不能为空！',
        ]);*/
        $data = input('post.');
        $data['mid'] = $this->mid;
        unset($data['token']);
        $arr = [
            'user_id'       => $this->mid,
            'cid'           => $data['cid'],
            'content'       => '评论了你的作品'
        ];
        $publisher = $this->app->db->name('DataNewsItem')->where('id='.$data['cid'])->value('publisher');
        if ($publisher !== $this->mid){
            $this->app->db->name('data_user_message')->insert($arr);
        }
        if ($this->app->db->name('DataNewsXComment')->insert($data) !== false) {
            NewsService::instance()->syncNewsTotal($data['cid']);
            $this->success('添加评论成功！');
        } else {
            $this->error('添加评论失败！');
        }
    }

    /**
     * 获取我的评论
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getComment()
    {
        $map['mid'] = $this->mid;
        $map['cid'] = input('cid');
        $result = $this->_query('DataNewsXComment')->where($map)->order('id desc')->page(true, false);
//        dump($result);die;
        NewsService::instance()->buildListByCidAndMidPage($result['list']);
        $this->success('获取评论列表成功', $result);
    }

    /**
     * 删除内容评论
     * @throws \think\db\exception\DbException
     */
    public function delComment()
    {
        /*$map = $this->_vali([
            'mid.value'   => $this->mid,
            'cid.require' => '文章ID不能为空！',
            'id.require'  => '评论ID不能为空！',
        ]);*/
        $map = input('post.');
        $map['mid'] = $this->mid;
        if ($this->app->db->name('DataNewsXComment')->where($map)->delete() !== false) {
            $this->success('评论删除成功！');
        } else {
            $this->error('认证删除失败！');
        }
    }

    /**
     * 添加内容收藏
     * @throws \think\db\exception\DbException
     */
    public function addCollect()
    {
        $map = $this->_getCollectWhere(1);
        if ($this->app->db->name('DataNewsXCollect')->where($map)->count() > 0) {
            $this->success('您已收藏！');
        }
        if ($this->app->db->name('DataNewsXCollect')->insert($map) !== false) {
            NewsService::instance()->syncNewsTotal($map['cid']);
            $this->success('收藏成功！');
        } else {
            $this->error('收藏失败！');
        }
    }

    /**
     * 取消收藏文章
     * @throws \think\db\exception\DbException
     */
    public function delCollect()
    {
        $map = $this->_getCollectWhere(1);
        if ($this->app->db->name('DataNewsXCollect')->where($map)->delete() !== false) {
            NewsService::instance()->syncNewsTotal($map['cid']);
            $this->success('取消收藏成功！');
        } else {
            $this->error('取消收藏失败！');
        }
    }

    /**
     * 获取会员收藏的资讯
     * @throws \think\db\exception\DbException
     */
    public function getCollect()
    {
        $map = ['mid' => $this->mid, 'type' => 1];
        $query = $this->_query('DataNewsXCollect')->where($map);
        $result = $query->order('id desc')->page(true, false, false, 15);
        NewsService::instance()->buildListByCidAndMid($result['list']);
        $this->success('获取收藏记录成功！', $result);
    }

    /**
     * 添加内容点赞
     * @throws \think\db\exception\DbException
     */
    public function addLike()
    {
        $map = $this->_getCollectWhere(2);
        if ($this->app->db->name('DataNewsXCollect')->where($map)->count() > 0) {
            $this->success('您已点赞！');
        }
        if ($this->app->db->name('DataNewsXCollect')->insert($map) !== false) {
            NewsService::instance()->syncNewsTotal($map['cid']);
            $this->success('点赞成功！');
        } else {
            $this->error('点赞失败！');
        }
    }

    /**
     * 取消内容点赞
     * @throws \think\db\exception\DbException
     */
    public function delLike()
    {
        $map = $this->_getCollectWhere(2);
        if ($this->app->db->name('DataNewsXCollect')->where($map)->delete() !== false) {
            NewsService::instance()->syncNewsTotal($map['cid']);
            $this->success('取消点赞成功！');
        } else {
            $this->error('取消点赞失败！');
        }
    }

    /**
     * 获取会员收藏的资讯
     * @throws \think\db\exception\DbException
     */
    public function getLike()
    {
        $map = ['mid' => $this->mid, 'type' => 2];
        $query = $this->_query('DataNewsXCollect')->where($map);
        $result = $query->order('id desc')->page(true, false, false, 15);
        NewsService::instance()->buildListByCidAndMid($result['list']);
        $this->success('获取点赞记录成功！', $result);
    }

    /**
     * 获取会员的浏览历史
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getHistory()
    {
        $map = ['a.mid' => $this->mid];
//        dump($map);
//        $query = $this->_query('DataNewsXHistory')->where($map);
//        $result = $query->order('id desc')->page(true, false, false, 15);
        $list = $this->app->db->name('data_news_x_history')
            ->alias('a')
            ->join('data_member b','a.mid=b.id')
            ->join('data_news_item c','a.cid=c.id')
            ->field('c.*,b.username,b.headimg,a.mid,a.create_at')
            ->order('a.create_at desc')
            ->where($map)
            ->paginate(sysconf('listrow'))
            ->toArray();

        foreach ($list['data'] as $key => $val){
            $val['like'] = $this->app->db->name('data_member_like')->where(['a_id' => $val['id'],'user_id' => $this->mid])->value('id');
            if (!empty($val['like'])){
                $list['data'][$key]['m_like'] = 1;
            }else{
                $list['data'][$key]['m_like'] = 2;
            }
            if (!empty($val['images'])){
                $list['data'][$key]['images'] = json_decode($val['images']);
            }
        }
//        NewsService::instance()->buildListByCidAndMid($result['list']);
        if (!empty($list['data'])){
            $this->success('获取成功',$list);
        }elseif ($list !== false){
            $this->error('没有更多了');
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * 获取收藏点赞
     * @param integer $type 数据类型
     * @return array
     */
    private function _getCollectWhere($type = 1): array
    {
        return $this->_vali([
            'mid.value'   => $this->mid,
            'type.value'  => $type,
            'cid.require' => '文章不能为空！',
        ]);
    }

    /**
     * 用户评论以及用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function newsXComment(){
        /*$data = $this->_vali([
            'cid.require'       => '未找到文章信息',
        ]);*/
        $data = input('post.');
        $commnets = $this->app->db->name('data_news_x_comment')
            ->alias('a')
            ->join('data_member b','a.mid = b.id')
            ->field("a.*,b.username,b.headimg")
            ->where('a.cid='.$data['cid'])
//            ->select();
            ->paginate(sysconf('listrow'));
        if (!empty($commnets)){
            $this->success('获取成功',$commnets);
        }else{
            $this->error('获取失败');
        }
    }

    /**
     * 二级点赞
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function addCommentLike(){
        /*$data = $this->_vali([
            'cmid.require'      => '未找到该评论内容',
            'mid.value'         => $this->mid,
            'content.require'   => '请输入评论内容'
        ]);*/
        $data = input('post.');
        $data['mid'] = $this->mid;
        unset($data['token']);
        $like = $this->app->db->name('data_comment_x_like')->where(['cmid' => $data['cmid'],'mid'=> $this->mid])->find();
        if ($like){
            $this->error('你已经点过赞了');
        }
        $result = $this->app->db->name('data_comment_x_like')->insert($data);
        if ($result){
            $this->success('点赞成功');
        }else{
            $this->error('点赞失败');
        }
    }

    /**
     * 添加二级评论
     */
    public function addCommentComment(){
        $data = input('post.');
        $data['mid'] = $this->mid;
        unset($data['token']);
        $result = $this->app->db->name('data_comment_x_comment')->insert($data);
        if ($result){
            $this->success('评论成功');
        }else{
            $this->error('评论失败');
        }
    }

    public function getCommentLike(){
        $data = $this->_vali([
            'cmid.require'      => '未找到该评论内容',
            'mid.value'         => $this->mid
        ]);
        $data = input('post.');
        unset($data['token']);
        $list = $this->app->db->name('data_comment_x_like')
            ->alias('a')
            ->join('data_news_x_comment b','a.cmid=b.id')
            ->field('a.*')
            ->where('cmid='.$data['cmid'])
            ->count();
        if ($list){
            $this->success('获取成功',$list);
        }else{
            $this->error('获取失败');
        }
    }

}